import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import SearchArea from 'components/search-area'
import { Table, Button, Popconfirm, Input, Form, Badge } from 'antd'
import creditManagementService from 'containers/credit-setting/credit-management/credit-management.service'
import constants from 'share/constants'
const { TextArea } = Input;
const FormItem = Form.Item;
import errorMessage from 'share/errorMessage'
import CancelDetail from 'containers/credit-setting/credit-management/cancel-detail'
import SlideFrame from 'components/slide-frame'
import moment from 'moment'
import Control from 'components/control'
class CreditEvent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchForm: [{
        type: 'list',
        id: 'user',
        label: messages('credit-setting.key14')/*员工*/,
        listType: 'user',
        labelKey: 'fullName',
        valueKey: 'userOID',
        single: true
      }, {
        type: 'input',
        id: 'businessCode',
        label: messages('credit-setting.key4')/*相关单据*/,
        placeholder: messages('credit-setting.key15')/*请输入单据号*/
      }, {
        type: 'input',
        id: 'comment',
        label: messages('credit-setting.key16')/*事件*/,
        placeholder: messages('credit-setting.key17')/*请输入事件描述*/
      }, {
        type: 'select',
        id: 'operationType',
        label: messages('credit-setting.key7')/*处理方式*/,
        options: constants.creditRuleOperation.map(item => ({ label: item.text, value: item.value }))
      }, {
        type: 'select',
        id: 'status',
        label: messages('common.column.status')/*状态*/,
        options: [{
          label: messages('common.status.enable')/*启用*/,
          value: 1001
        }, { label: messages('credit-setting.key9')/*作废*/, value: 1002 }]
      }, {
        type: 'searcher',
        id: 'modelId',
        label: messages('credit-setting.key107')/*信用模型*/,
        listType: 'credit_model_list',
        labelKey: 'modelName',
        valueKey: 'id',
        descriptionKey:'modelCode',
      }],
      columns: [{
        title: messages('credit-setting.key14')/*员工*/, dataIndex: 'fullName'
      }, {
        title: messages('credit-setting.key4')/*相关单据*/, dataIndex: 'businessCode'
      }, {
        title: messages('credit-setting.key5')/*事件描述*/, dataIndex: 'comment'
      }, {
        title: messages('credit-setting.key6')/*信用规则*/, dataIndex: 'ruleCondition'
      }, {
        title: messages('credit-setting.key3')/*信用类型*/,
        dataIndex: 'modelTypeId',
        render: modelTypeId => messages('credit-setting.key13')/*报销信用*/
      }, {
        title: messages('credit-setting.key7')/*处理方式*/,
        dataIndex: 'operationType',
        render: operationType => constants.getTextByValue(operationType, 'creditRuleOperation')
      }, {
        title: messages('credit-setting.key8')/*处理结果*/, dataIndex: 'changeRank', render: (text, record) =>
          `${record.operationType % 2 === 0 ? '-' : '+'}${record.operationType > 1002 ? record.changeRank : record.changeScore}`
      }, {
        title: messages('credit-setting.key18')/*更新时间*/,
        dataIndex: 'createdDate',
        render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
      }, {
        title: messages('credit-setting.key11')/*处理人*/, dataIndex: 'operatorName'
      }, {
        title: messages('common.column.status')/*状态*/, dataIndex: 'status', render: status => (
          <Badge status={status === 1001 ? 'success' : 'error'}
                 text={status === 1001 ? messages("common.status.enable") : messages('credit-setting.key9')/*作废*/}/>)
      }, {
        title: messages('common.operation')/*操作*/, dataIndex: 'operate', render: (text, record) => {
          //这期不要作废，先拿出来
          let disabled = (
            <Popconfirm
              overlayStyle={{ width: 300 }}
              title={
                <div> {messages('credit-setting.key19')/*作废后无法恢复，确定要作废吗？*/}<br/>
                  <FormItem label="理由" required>
                    <TextArea rows={2} value={this.state.cancelReason} onChange={this.handleChangeReason}/>
                  </FormItem>
                </div>
              }
              onConfirm={() => this.disableRecord(record)}
              okText={messages('credit-setting.key20')/*确认*/}
              cancelText={messages('common.cancel')/*取消*/}
              onCancel={() => this.setState({ cancelReason: '' })}>
              <a>{messages('credit-setting.key9')/*作废*/}</a>
            </Popconfirm>
          );
          if (record.status === 1001)
            return <Control><a data-control="credit-management.disabled" onClick={() => this.editEvent(record)}>{messages('common.edit')/*编辑*/}</a></Control>;
          else
            return <a onClick={() => this.setState({
              nowData: record,
              showSlideFrame: true
            })}>{messages('common.view')/*查看*/}</a>
        }
      }],
      cancelReason: '',
      pagination: {
        total: 0
      },
      page: 0,
      size: 10,
      data: [],
      loading: false,
      searchParams: {},
      showSlideFrame: false,
      nowData: {}
    }
  }

  handleChangeReason = e => {
    this.setState({ cancelReason: e.target.value })
  };

  componentDidMount() {
    let nowUser = this.props.nowUser;
    if (nowUser.userOID) {
      this.formRef.setValues({
        user: [nowUser],
        businessCode: null,
        comment: null,
        operationType: null,
        status: null
      });
      this.setState({ searchParams: { userOID: nowUser.userOID }, page: 0 }, this.getList)
    } else {
      this.getList();
    }
  }

  getList = () => {
    const { page, size, searchParams } = this.state;
    const { nowUser } =  this.props;
    this.setState({ loading: true });
    creditManagementService.getCreditEvents(Object.assign({}, searchParams, {
      page, size, setOfBooksId: nowUser.setOfBooksId
    })).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({ page: page - 1 }, this.getList)
  };

  search = result => {
    if (result.user && result.user.length > 0) {
      result.userOID = result.user[0];
      delete result.user;
    }
    this.setState({ searchParams: result, page: 0 }, this.getList)
  };

  clear = () => {
    this.setState({ searchParams: {}, page: 0 }, this.getList)
  };

  handleNew = () => {
    this.props.onCreate();
  };

  disableRecord = record => {
    this.setState({ loading: true });
    creditManagementService.disableRecord(record.id, this.state.cancelReason).then(res => {
      this.setState({ cancelReason: '' });
      this.getList();
    }).catch(e => {
      errorMessage(e.response);
    });
  };

  wrapValue = record => {
    let values = record;
    values.user = [{ userOID: record.userOID, fullName: record.fullName }];
    values.entity = [{ businessCode: record.businessCode }];
    values.creditCondition = [{
      id: record.conditionId,
      ruleCondition: record.ruleCondition,
      operationType: record.operationType,
      changeScore: record.changeScore,
      changeRank: record.changeRank
    }];
    return values;
  };

  editEvent = record => {
    this.props.onEdit(this.wrapValue(record));
  };

  render() {
    const { searchForm, pagination, columns, loading, data, showSlideFrame, nowData } = this.state;
    const { tenantMode } = this.props;
    return (
      <Control>
        <div>
          <SearchArea
            searchForm={searchForm}
            submitHandle={this.search}
            clearHandle={this.clear}
            wrappedComponentRef={(inst) => this.formRef = inst}
          />
          <div className="table-header">
            <div className="table-header-title">{messages('common.total', { total: `${pagination.total}` })}</div>
            {/*共搜索到*条数据*/}
            <div data-control="credit-management.hidden" className="table-header-buttons">
              <Button type="primary" onClick={this.handleNew}>{messages('common.create')}</Button>
            </div>
          </div>
          <Table
            columns={columns}
            size="middle"
            bordered
            rowKey="id"
            pagination={pagination}
            loading={loading}
            dataSource={data}
          />
          <SlideFrame
            show={showSlideFrame}
            content={CancelDetail}
            onClose={() => this.setState({ showSlideFrame: false })}
            params={{ data: nowData }}
            title={messages('credit-setting.key21')/*查看信用事件*/}
          />

        </div>
      </Control>
    )
  }
}

CreditEvent.contextTypes = {
  router: React.PropTypes.object
};

CreditEvent.propTypes = {
  onCreate: React.PropTypes.func,
  onEdit: React.PropTypes.func,
  nowUser: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(CreditEvent)
